package com.genesis.web.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.genesis.mall.common.Result;
import com.genesis.mall.entity.UmsMember;
import com.genesis.mall.service.IUmsMemberService;
import com.genesis.mall.utils.TokenUtil;
import com.genesis.mall.utils.ValidateCodeUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author Hshuai
 * @since 2022-08-01
 */

@Slf4j
@RestController
@RequestMapping("/sso")
public class UmsMemberController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IUmsMemberService memberService;

    /**
     * 发送验证码
     *
     * @param telephone
     * @return
     */
    @GetMapping("/getAuthCode")
    public Result getAuthCode(String telephone) {

        if (StringUtils.isNotEmpty(telephone)) {
            //手机号码不为空 生成验证码
            String code = ValidateCodeUtils.generateValidateCode(6).toString();
            log.info("验证码:{}", code);

            //调用阿里云提供的短信服务API完成发送短信
            // SMSUtils.sendMessage("阿里云短信测试", "SMS_154950909", phone, code);
            //设置验证码缓存存活时间5分钟
            redisTemplate.opsForValue().set(telephone, code, 2, TimeUnit.MINUTES);
            return Result.success(code);
        }
        return Result.error("验证码发送失败");

    }

    /**
     * 会员登录
     *
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestParam String username, @RequestParam String password) {
        return memberService.login(username, password);

    }

    /**
     * 获取用户信息
     *
     * @param request
     * @return
     */
    @GetMapping("/info")
    public Result info(HttpServletRequest request) {
        //获取用户id
        String authorization = request.getHeader("Authorization");
        String token = authorization.substring(6);
        Claims claims = TokenUtil.getClaims(token);
        Long umsMemberId = Long.parseLong(claims.get("umsMember").toString());

        return Result.success(memberService.getById(umsMemberId));

    }

    /**
     * 会员注册
     * @param authCode
     * @param password
     * @param telephone
     * @param username
     * @return
     */
    @PostMapping("/register")
    public Result register(@RequestParam String authCode,
                           @RequestParam String password,
                           @RequestParam String telephone,
                           @RequestParam String username) {

        if(authCode==null){
            return Result.error("验证码不可为空");
        }
        //从redis中获取验证码
        String redisCode = (String) redisTemplate.opsForValue().get(telephone);
        if (!authCode.equals(redisCode)) {
            return Result.error("验证码输入错误");
        }
        LambdaQueryWrapper<UmsMember> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsMember::getUsername,username);
        int count1 = memberService.count(lqw);
        if (count1>0){
            return Result.error("用户名已经存在");
        }
        LambdaQueryWrapper<UmsMember> lqw2 = new LambdaQueryWrapper<>();
        lqw2.eq(UmsMember::getPhone,telephone);
        int count2 = memberService.count(lqw2);
        if (count2>0){
            return Result.error("该号码已注册");
        }

        // 密码长度不少于8位且至少包含大写字母、小写字母、数字和特殊符号中的四种
      // String password1 = "^(?![A-Za-z0-9]+$)(?![a-z0-9\\W]+$)(?![A-Za-z\\W]+$)(?![A-Z0-9\\W]+$)[a-zA-Z0-9\\W]{8,}$";
        // 密码长度6-20位且至少包含大写字母、小写字母、数字或特殊符号中的任意三种
        String passwordFormat = "^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{6,20}$";

         if (!password.matches(passwordFormat)){
             return Result.error("密码长度6-20位且至少包含大写字母、小写字母、数字或特殊符号中的任意三种");
         }
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername(username);
        umsMember.setPhone(telephone);
        umsMember.setStatus(1);
        umsMember.setMemberLevelId(4L);
        umsMember.setCreateTime(LocalDateTime.now());
        //通过BCrypt对密码进行加密
        String encodePassword = BCrypt.hashpw(password, BCrypt.gensalt());
        umsMember.setPassword(encodePassword);
        //完成注册
        memberService.save(umsMember);
        return Result.success();


    }


    /**
     * 会员修改密码
     * @param authCode
     * @param password
     * @param telephone
     * @return
     */
    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestParam String authCode,
                                 @RequestParam String password,
                                 @RequestParam String telephone){

        if(authCode==null){
            return Result.error("验证码不可为空");
        }
        //从redis中获取验证码
        String redisCode = (String) redisTemplate.opsForValue().get(telephone);
        if (!authCode.equals(redisCode)) {
            return Result.error("验证码输入错误");
        }

        LambdaQueryWrapper<UmsMember> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsMember::getPhone,telephone);
        UmsMember umsMember = memberService.getOne(lqw);
        if (umsMember==null){
            return Result.error("号码不存在");
        }
        //密码验证
        String passwordFormat = "^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_]+$)(?![a-z0-9]+$)(?![a-z\\W_]+$)(?![0-9\\W_]+$)[a-zA-Z0-9\\W_]{6,20}$";
        if (!password.matches(passwordFormat)){
            return Result.error("密码长度6-20位且至少包含大写字母、小写字母、数字或特殊符号中的任意三种");
        }
        //通过BCrypt对密码进行加密
        String encodePassword = BCrypt.hashpw(password, BCrypt.gensalt());
        umsMember.setPassword(encodePassword);
        //修改密码
        memberService.updateById(umsMember);
        return Result.success();



    }

}
